package com.tcgroup.phone.base_core.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ViewDataBinding;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

/**
 * 作者: wangfei
 * 创建时期: 2020/3/18.
 * 包名: com.tcgroup.phone.base_core.adapter
 * 类名: OSAndroidMvvm
 */
public abstract class BaseBindAdapter<T, B extends ViewDataBinding> extends RecyclerView.Adapter {

    protected Context context;
    protected ObservableArrayList<T> items;
    protected OnItemClickListener mItemClickListener;
    protected OnItemLongClickListener mOnItemLongClickListener;

    @Override
    public int getItemCount() {
        return items != null && items.size() > 0 ? items.size() : 0;
    }


    public BaseBindAdapter(Context context, ObservableArrayList<T> items) {
        this.context = context;
        this.items = items;
    }

    public BaseBindAdapter(Context context, ArrayList<T> items) {
        this.context = context;
        ObservableArrayList arrayList = new ObservableArrayList();
        arrayList.addAll(items);
        this.items = arrayList;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        B binding = DataBindingUtil.inflate(LayoutInflater.from(this.context),
                getLayoutItemId(viewType),parent,false);
        return new BaseBindingViewHolder(binding.getRoot());
    }

    public class BaseBindingViewHolder extends RecyclerView.ViewHolder {
        public BaseBindingViewHolder(View itemView) {
            super(itemView);
        }
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        B binding = DataBindingUtil.getBinding(holder.itemView);
        onBindItem(binding,items.get(position),position);
    }

    public interface OnItemClickListener<T> {
        void onItemClick(T e, int position,int style);
    }
    public interface OnItemLongClickListener<E> {
        boolean onItemLongClick(E e, int postion);
    }

    public void setItemClickListener(OnItemClickListener itemClickListener) {
        mItemClickListener = itemClickListener;
    }

    public void setOnItemLongClickListener(OnItemLongClickListener onItemLongClickListener) {
        mOnItemLongClickListener = onItemLongClickListener;
    }

    @LayoutRes
    protected abstract int getLayoutItemId(int viewType);

    protected abstract void onBindItem(B binding, T item,int position);

}
